﻿using AutoMapper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using housingsafety.server.Caching.Core;
using housingsafety.server.Entities;
using housingsafety.server.Entities.DataModels;
using housingsafety.server.Helpers;
using housingsafety.server.Models;
using housingsafety.server.Repository;
using housingsafety.server.Repository.Extensions;
using housingsafety.server.Svcs;

namespace housingsafety.server.Controllers
{
    /// <summary>
    /// 地名地址服务
    /// </summary>
    public class AddressController : BaseController<AddressController>
    {
        AddressServiceConfig addressServerConfig;

        public AddressController(
            ILogger<AddressController> logger
            , IOptions<AddressServiceConfig> addressOptions
            , IRepository<ZmSystemLog> systemLogRepository) : base(logger, systemLogRepository)
        {
            addressServerConfig = addressOptions.Value;
        }


        /// <summary>
        /// 地名查询
        /// </summary>
        /// <param name="key"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        [HttpGet("address/query")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<List<ZealMapAddress>>), 200)]
        [AllowAnonymous]
        public RespRet<List<ZealMapAddress>> Query([FromQuery] string key, [FromQuery] int pageIndex,[FromQuery] int limit)
        {
            var client = new RestClient("https://api.map.baidu.com");
            var request = new RestRequest($"/place/v2/search?query={key}&region=全国&output=json&ret_coordtype=gcj02ll&page_size={limit}&page_num={pageIndex}&ak={addressServerConfig.baiduAK}", DataFormat.Json);
            var response = client.Get<BaiduAddressQueryResponse>(request);
            if(response.StatusCode != System.Net.HttpStatusCode.OK)
            {
                Logger.LogError("baidu address bad request");
                return new RespRet<List<ZealMapAddress>>(false, "trd server bad request!");
            }

            var data = response.Data;
            if(data.status != 0)
            {
                Logger.LogError($"baidu address bad request:{data.message}");
                return new RespRet<List<ZealMapAddress>>(false, "trd server bad request!");
            }

            var rtnList = new List<ZealMapAddress>();
            foreach(var baiduAddress in data.results)
            {
                var zm = new ZealMapAddress();
                zm.Desc = baiduAddress.name;
                zm.lat = baiduAddress.location?.lat??0;
                zm.lng = baiduAddress.location?.lng??0;
                zm.address = baiduAddress.address;
                zm.province = baiduAddress.province;
                zm.city = baiduAddress.city;
                zm.area = baiduAddress.area;
                zm.MatchNum = baiduAddress.num;
                rtnList.Add(zm);
            }

            return new RespRet<List<ZealMapAddress>>(true,"success", rtnList);
        }

        /// <summary>
        /// 地理逆编码（通过坐标查地名）
        /// </summary>
        /// <param name="lat"></param>
        /// <param name="lng"></param>
        /// <returns></returns>
        [HttpGet("address/regeo")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<string>), 200)]
        public RespRet<string> QueryGeo([FromQuery] double lat, [FromQuery] double lng)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// 地理编码接口（通过地名查坐标)，支持批量
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost("address/geo/batch")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<string>), 200)]
        [AllowAnonymous]
        public RespRet<List<BatchAddressGeoCodingItem>> QueryGeo([FromBody] BatchAddressGeoCodingRequest re)
        {
            var client = new RestClient("http://api.tianditu.gov.cn");
            List<BatchAddressGeoCodingItem> list = new List<BatchAddressGeoCodingItem>();
            foreach (var add in re.AddressList)
            {
                var request = new RestRequest("/geocoder?ds={\"keyWord\":\"" + add + "\"}&tk=0c940d8266bda9f4fdd9accf5564c150", DataFormat.Json);
                var response = client.Get<string>(request);
                if (response.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    var stringJson = response.Content;
                   var data =  Newtonsoft.Json.JsonConvert.DeserializeObject<TiandiTuGeocodingResponse>(stringJson);
                    if (data.status == 0)
                    {
                        var item = new BatchAddressGeoCodingItem();
                        item.Address = add;
                        item.Lat = data.location.lat;
                        item.Lng = data.location.lon;
                        list.Add(item);
                    }
                }
                //防止被天地图拉入黑名单
                Thread.Sleep(200);
            }

            return new RespRet<List<BatchAddressGeoCodingItem>>(true, "success", list);

        }


       
    }
}
